/*
 * @Description: 吸顶组件
 * @Author: Yong
 * @Date: 2021-09-26 17:22:43
 * @LastEditTime: 2021-09-26 17:35:43
 */
import React from 'react'
import styles from './index.module.css'

export default class Sticky extends React.Component {

    // 创建ref对象
    placeholder = React.createRef()
    content = React.createRef()

    handleScroll = () => {
        // 获取DOM对象
        const placeholderEl = this.placeholder.current
        const contentEl = this.content.current
        const { height } = contentEl.getBoundingClientRect()
        const { top } = placeholderEl.getBoundingClientRect()
        if (top < 0) {
            // 吸顶
            contentEl.classList.add(styles.fixed)
            placeholderEl.style.height = `${height}px`
        } else {
            // 取消吸顶
            contentEl.classList.remove(styles.fixed)
            placeholderEl.style.height = '0px'
        }
    }

    componentDidMount () {
        window.addEventListener('scroll', this.handleScroll)
    }
    componentWillUnmount () {
        window.removeEventListener('scroll', this.handleScroll)
    }

    render () {
        return (
            <div className={styles.sticky}>
                {/* 占位元素 */}
                <div ref={this.placeholder}></div>
                {/* 内容元素 */}
                <div ref={this.content}>{this.props.children}</div>
            </div>
        )
    }
}